﻿using LitJson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Security;
using System.Security.Cryptography;

namespace CrabSS_M
{
    /// <summary>
    /// auth.xaml 的交互逻辑
    /// </summary>
    public class RootObject
        {
            public string? data { get; set; }
    public int retCode { get; set; }
}
public class settinginfo //把我整不会了😅
    {
        public string? WindowTitle { get; set; }
        public string? Server1 { get; set; }
        public string? Server2 { get; set; }
        public string? Server3 { get; set; }
        public string? Server4 { get; set; }
        public string? Server5 { get; set; }
        public string? authcode { get; set; }
    }
    public partial class auth : Window
    {
        public static string Base64Encode(string source)
        {
            return Base64Encode(Encoding.UTF8, source);
        }

        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="encodeType">加密采用的编码方式</param>
        /// <param name="source">待加密的明文</param>
        /// <returns></returns>
        public static string Base64Encode(Encoding encodeType, string source)
        {
            string encode = string.Empty;
            byte[] bytes = encodeType.GetBytes(source);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = source;
            }
            return encode;
        }

        /// <summary>
        /// Base64解密，采用utf8编码方式解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string Base64Decode(string result)
        {
            return Base64Decode(Encoding.UTF8, result);
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="encodeType">解密采用的编码方式，注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public static string Base64Decode(Encoding encodeType, string result)
        {
            string decode = string.Empty;
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encodeType.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }
        public auth()
        {
            InitializeComponent();
            if (!File.Exists("settings.json"))
            {//初始化Json部分
                try
                {
                    settinginfo settings = new settinginfo();
                    string json = JsonMapper.ToJson(settings); //using LitJson
                    StreamWriter sw = new StreamWriter(System.Environment.CurrentDirectory + "\\settings.json");
                    sw.Write(json);
                    sw.Close();
                    string strJson = File.ReadAllText("settings.json", Encoding.UTF8);
                    JObject oJson = JObject.Parse(strJson); //using Newtonsoft.Json.Linq
                    oJson["WindowTitle"] = "CrabSS | 服务器管理中心";
                    oJson["Server1"] = null;
                    oJson["Server2"] = null;
                    oJson["Server3"] = null;
                    oJson["Server4"] = null;
                    oJson["Server5"] = null;
                    oJson["authCode"] = null;
                    string strConvert = Convert.ToString(oJson); //将json装换为string
                    File.WriteAllText("settings.json", strConvert); //将内容写进json文件中
                    sw.Dispose();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("发生错误：" + ex.ToString(), "关键错误", MessageBoxButton.OK, MessageBoxImage.Hand, MessageBoxResult.OK);
                    Close();
                }
            }
            else
            {
                settinginfo readed = new settinginfo();
                using (StreamReader readFile = File.OpenText("settings.json"))
                {
                    using (JsonTextReader reader = new JsonTextReader(readFile)) //using Newtonsoft.Json
                    {
                        JObject oJson = (JObject)JToken.ReadFrom(reader);
                        string? authCode = readed.authcode = (string?)oJson["authCode"];
                        reader.Close();
                        if (authCode == null)
                        {
                            return;
                        }
                        else
                        {
                            Dictionary<string, string>post = new Dictionary<string,string>();
                            string m = Base64Decode(authCode);
                            post.Add("authid",m);
                            var r = lingqi.Post("https://v6.crabapi.cn/api/crabss/auth",post);
                            RootObject rb = JsonConvert.DeserializeObject<RootObject>(r);
                            if (rb.retCode == 0)
                            {
                                Close();
                            }
                            else
                            {
                                MessageBox.Show(rb.data, "失败了捏，需要重新输入码", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }
                        }
                    }
                }
            }
        }

        private void knowabout_Click(object sender, RoutedEventArgs e)
        {

        }

        private void reg_Click(object sender, RoutedEventArgs e)
        {
            Dictionary<string, string> post = new Dictionary<string, string>();
            post.Add("authid", FloatingPasswordBox.Password);
            var r = lingqi.Post("https://v6.crabapi.cn/api/crabss/auth", post);
            RootObject rb = JsonConvert.DeserializeObject<RootObject>(r);
            if (rb.retCode == 0)
            {
                settinginfo settings = new settinginfo();
                string json = JsonMapper.ToJson(settings); //using LitJson
                StreamWriter sw = new StreamWriter(System.Environment.CurrentDirectory + "\\settings.json");
                sw.Write(json);
                sw.Close();
                string strJson = File.ReadAllText("settings.json", Encoding.UTF8);
                JObject oJson = JObject.Parse(strJson); //using Newtonsoft.Json.Linq
                oJson["WindowTitle"] = "CrabSS | 服务器管理中心";
                oJson["Server1"] = null;
                oJson["Server2"] = null;
                oJson["Server3"] = null;
                oJson["Server4"] = null;
                oJson["Server5"] = null;
                oJson["authCode"] = Base64Encode(FloatingPasswordBox.Password);
                string strConvert = Convert.ToString(oJson); //将json装换为string
                File.WriteAllText("settings.json", strConvert); //将内容写进json文件中
                sw.Dispose();
                Close();
            }
            else
            {
                MessageBox.Show(rb.data, "失败了捏，需要重新输入码", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }
    }
}
